package com.caiyigo.struts.action;

import java.util.List;

import org.apache.log4j.Logger;

import com.caiyigo.struts.model.Department;
import com.caiyigo.struts.model.Employee;
import com.caiyigo.struts.service.IDepartmentService;
import com.caiyigo.struts.service.IEmployeeService;
import com.caiyigo.struts.serviceImpl.DepartmentServiceImpl;
import com.caiyigo.struts.serviceImpl.EmployeeServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * 
 * @author xdwang
 * 
 * @date 2012-6-6 下午5:03:17
 * 
 * @email xdwangiflytek@gmail.com
 * 
 * @blog xdwangiflytek.iteye.com
 * 
 *       员工的Action
 * 
 */
public class EmployeeAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(EmployeeAction.class
			.getName());
	private static IEmployeeService empService = new EmployeeServiceImpl();
	private static IDepartmentService deptService = new DepartmentServiceImpl();
	private Employee employee;
	private List<Employee> employees;

	private List<Department> departments;

	/**
	 * Ensures that the collection of Department objects is always available to
	 * the view.
	 */
	public void prepare() throws Exception {
		departments = deptService.getAllDepartments();

		logger.debug("in method prepare");

	}

	/**
	 * Saves a new employee if the employee object's employeeId is null
	 * otherwise updates existing employee.
	 * 
	 * @return success
	 */
	public String save() {
		logger.debug("in method save");

		if (employee.getEmployeeId() == null) {
			empService.insertEmployee(employee);
		} else {
			empService.updateEmployee(employee);
		}
		return Refresh_List;
	}

	/**
	 * Gets a specific Employee objects so it can be displayed in the view.
	 * 
	 * @return input
	 */
	public String input() {
		logger.debug("in method input");

		if (employee != null && employee.getEmployeeId() != null) {
			logger.debug("Employee ID is " + employee.getEmployeeId());
			employee = empService.getEmployee(employee.getEmployeeId());
		}
		return INPUT;
	}

	public String delete() {
		logger.debug("in method delete");

		if (employee != null && employee.getEmployeeId() != null) {
			logger.debug("Employee ID is " + employee.getEmployeeId());

		}
		empService.deleteEmployee(employee.getEmployeeId());

		return Refresh_List;
	}

	public String execute() throws Exception {
		setEmployees(empService.getAllEmployees());

		return SUCCESS;

	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public List<Department> getDepartments() {
		return departments;
	}

	public List<Employee> getEmployees() {
		return employees;
	}

	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}
}
